/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.Capbac;
import bc.entity.Congty;
import bc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class CongtyDAO {

    private Session session;

    public CongtyDAO() {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        this.session = factory.getCurrentSession();
    }

    public Congty[] getAllCongty() {
        try {
            session.getTransaction().begin();
            String sql = "from Congty";
            Query query = session.createQuery(sql);
            List result = query.list();
            Congty[] congtyList = new Congty[result.size()];
            result.toArray(congtyList);
            session.flush();
            session.getTransaction().commit();
            return congtyList;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;

    }

    public String getTenCongty(int id_congty) {
        try {
            session.getTransaction().begin();
            String sql = "from Congty where id_congty = ?";
            Query query = session.createQuery(sql);
            query.setInteger(0, id_congty);
            Congty result = (Congty) query.uniqueResult();
            String congty = result.getCongty();
            session.flush();
            session.getTransaction().commit();
            return congty;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return "";
    }
// cua nga
    public List<Congty> getCongtyLikesName(String name) {
        try {
            session.getTransaction().begin();
            String sql = "from Congty where congty like ?";
            Query query = session.createQuery(sql);
            query.setString(0, "%" + name + "%");
            List rs = query.list();
           // Congty[] arrct = new Congty[rs.size()];
           // rs.toArray(arrct);
            session.flush();
            return rs;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();

        }
        return null;
    }

    public static void main(String[] args) {
        CongtyDAO a = new CongtyDAO();
        System.out.println(a.getTenCongty(4));
    }
}
